CISC 1110 Lab 18b Bubble Sort
Here is the basic bubble sort code.
do {
swapped = false;
for (int pos = 0; pos < n - 1; pos++)
if (numb[pos] > numb[pos+1]) {
// swap 'em
temp = numb[pos];
numb[pos] = numb[pos+1];
numb[pos+1] = temp;
swapped = true;
}
} while(swapped == true);
Turn this code into a function, bubblesort, which receives 2 parameters: numb, an array of integers and n, the number of filled positions in the array. You will need to add the declarations for swapped and temp.
Insert the bubblesort function into the program you wrote for Lab 18a, replacing linearsort with bubblesort. Remember that Lab 18a declared and initialized an array, called the sort function, and printed the sorted array in the main program.
In your array declaration, make sure that at least two values in the array are the same. Call the sort function and make sure that the function sorts.
Then–one at a time–make the modifications shown in a, b, and c, and run the program. Observe your results. What happened in each case, and why?
a. Omit the very last statement swapped = true; from the set of statements done when numbers have to be swapped. (So you would use just three statements instead of the four shown above.)
b. Use the following if condition to compare two items [instead
of: if (numb[pos] > numb[pos+1]) ]. (Do you see
what is different?) HINT: put a print statement anywhere inside the bubblesort function to see what is happening.
if (numb[pos] >= numb[pos + 1]) {
c. Remove the = that you put in for part b.
Now remove the statement swapped = false; from its current location and put in the clause
else swapped = false; after the closing brace of the swap.